package cn.wgx.module.sys.service;

import cn.wgx.common.base.IBaseService;
import cn.wgx.common.entity.ent.EntUser;
import cn.wgx.common.entity.sys.*;
import cn.wgx.common.security.client.config.entity.LoginAppUser;
import cn.wgx.module.ent.constant.PublicEnterprise;
import cn.wgx.module.ent.service.EntUserService;
import cn.wgx.module.sys.mapper.UserMapper;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.toolkit.SqlHelper;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

@Service
public class UserService extends IBaseService<UserMapper, SysUser> {

    @Autowired
    private PasswordEncoder passwordEncoder;
    @Autowired
    private RoleService roleService;
    @Autowired
    private PermissionService permissionService;
    @Autowired
    private UserRoleService userRoleService;
    @Autowired
    private EntUserService entUserService;

    public List<SysUser> getListByIds(List<Integer> id) {
        return filter(baseMapper.selectBatchIds(id));
    }

    /**
     * 新建用户
     */
    @Transactional
    public boolean save(SysUser entity) {
        //密码加密处理
        entity.setMima(passwordEncoder.encode(entity.getMima()));
        if (StringUtils.isNotBlank(entity.getPayMima())) {
            entity.setPayMima(passwordEncoder.encode(entity.getPayMima()));
        }
        boolean s = SqlHelper.retBool(getBaseMapper().insert(entity));
        if (s) {
            ini(entity);
        }
        return s;
    }


    @Transactional(readOnly = true)
    public LoginAppUser getUserByName(String username) {
        SysUser sysUser = new SysUser();
        sysUser.setUsername(username);
        QueryWrapper<SysUser> queryWrapper = new QueryWrapper<>(sysUser);
        queryWrapper.last("LIMIT 1");
        SysUser one = getOne(queryWrapper);
        return fillPermission(one);
    }

    @Transactional(readOnly = true)
    public LoginAppUser getUserByMobile(String mobile) {
        SysUser sysUser = new SysUser();
        sysUser.setPhone(mobile);
        QueryWrapper<SysUser> queryWrapper = new QueryWrapper<>(sysUser);
        queryWrapper.last("LIMIT 1");
        SysUser one = getOne(queryWrapper);
        return fillPermission(one);
    }

    //过滤敏感信息
    public List<SysUser> filter(List<SysUser> list) {
        if (list == null || list.isEmpty()) {
            return list;
        }
        for (SysUser sysUser : list) {
            filter(sysUser);
        }
        return list;
    }

    public SysUser filter(SysUser sysUser) {
        sysUser.setMima(null);
        sysUser.setPayMima(null);
        return sysUser;
    }


    private LoginAppUser fillPermission(SysUser sysUserByName) {
        if (sysUserByName != null) {
            LoginAppUser loginAppUser = new LoginAppUser();
            BeanUtils.copyProperties(sysUserByName, loginAppUser);
            Set<Role> sysRoles = roleService.findRolesByUserId(sysUserByName.getUser_id());
            loginAppUser.setSysRoles(sysRoles);
            if (!CollectionUtils.isEmpty(sysRoles)) {
                Set<Long> roleIds = sysRoles.parallelStream().map(r -> r.getRole_id()).collect(Collectors.toSet());
                Set<Permission> sysPermissions = permissionService.findByRoleIds(roleIds);
                if (!CollectionUtils.isEmpty(sysPermissions)) {
                    Set<String> permissions = sysPermissions.parallelStream().map(p -> p.getUrl())
                            .collect(Collectors.toSet());

                    loginAppUser.setPermissions(permissions);// 设置权限集合
                }

            }
            return loginAppUser;
        }
        return null;
    }

    @Transactional
    public int resetMima(String username) {
        SysUser sysUser = new SysUser();
        sysUser.setMima(passwordEncoder.encode("123456"));
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq("username", username);
        return baseMapper.update(sysUser, queryWrapper);
    }

    @Transactional
    public int updateMima(Integer user_id, String oldPassword, String newPassword) {
        SysUser sysUser1 = new SysUser();
        sysUser1.setMima(passwordEncoder.encode(newPassword));
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq("user_id", user_id);
        SysUser sysUser2 = baseMapper.selectOne(queryWrapper);
        int i = 0;
        if (passwordEncoder.matches(oldPassword, sysUser2.getMima())) {
            i = baseMapper.update(sysUser1, queryWrapper);
        }
        return i;
    }

    @Transactional
    public int updateStatus(SysUser sysUser) {
        SysUser sysUser1 = new SysUser();
        sysUser1.setUser_id(sysUser.getUser_id());
        sysUser.setStatus(sysUser.getStatus());
        return baseMapper.updateById(sysUser);
    }

    @Transactional
    public SysUser updateFilter(SysUser sysUser) {
        int i = baseMapper.updateById(filter(sysUser));
        if (i > 0) {
            SysUser byId = getById(sysUser.getUser_id());
            return byId;
        }
        return null;
    }

    //创建用户之后需要初始化的信息
    public void ini(SysUser sysUser) {
        //默认添加普通用户权限
        UserRole userRole = new UserRole();
        userRole.setUser_id(sysUser.getUser_id());
        userRole.setRole_id(2);
        userRoleService.save(userRole);
        //加入公共企业
        EntUser entUser = new EntUser();
        entUser.setUser_id(sysUser.getUser_id());
        entUser.setEnt_id(PublicEnterprise.ENT_ID);
        entUser.setEntCode(PublicEnterprise.ENT_CODE);
        entUserService.save(entUser);
    }

    //包装列表
    public List<DTOSysUser> getUserList(Page page, Wrapper<SysUser> queryWrapper) {
        IPage<SysUser> e = getBaseMapper().selectPage(page, queryWrapper);
        List<DTOSysUser> dTOSysUsers = new ArrayList<>();
        for (SysUser sysUser : e.getRecords()) {
            dTOSysUsers.add(wrap(sysUser));
        }
        return dTOSysUsers;
    }

    //包装通用
    public DTOSysUser wrap(SysUser sysUser) {
        if (null == sysUser) {
            return null;
        }
        DTOSysUser dtoEntUser = new DTOSysUser();
        BeanUtils.copyProperties(sysUser, dtoEntUser);
        if (sysUser.getUser_id() != null) {
//            Enterprise enterprise = enterpriseService.getByCode(sysUser.getEntCode());
//            if (enterprise != null) {
//                dtoEntUser.setEntname(enterprise.getName());
//            }

        }
        return dtoEntUser;
    }

}
